import sys
import os

import pyglet.window
from pyglet.window.event import *
from pyglet.GL.VERSION_1_1 import *
from pyglet.GLU.VERSION_1_1 import *
from pyglet import clock
from pyglet.scene2d import Image2d
from pyglet.scene2d.textsprite import *
from pyglet.text import *
from pyglet.window.event import *
from ctypes import *


class TextSprite(TextSprite):
    autoscroll = True

#image = Image2d.load(sys.argv[1])

class Displayer(EventHandler):
    rotate = False
    starangle = 0
    angle = 0
    colour = (0, 1, 0, 0.75) 
    font = 'Arial'
    stars = []

    def __init__(self, texts):
        self.text = []
        self.texts = iter(texts)

    def next_text(self):
        font = Font(self.font, 24, bold=True)
        try:
            self.text += self.genText(self.texts.next(), font)
        except StopIteration:
            pass

    def on_text(self, text):
        print "text", repr(text)
        if text == 'r': 
            print 'rotating'
            self.rotate = True
        elif text == 'c':
            self.colour = (1, 1, 0, 0.75) 
        elif text == 'f':
            pass # change to SW font
        elif text == 'p':
            pass # play the music
        elif text == 's':
            self.stars = self.gen_stars()

    def on_mouse_press(self, button, x, y, modifiers):
        print "button", button
        if button == 1:
            self.next_text()

    def render(self):
        glClear(GL_COLOR_BUFFER_BIT)
        glLoadIdentity()
        glTranslatef(-350/2, 0, -600.)
        if self.stars:
            self.starangle += 0.08
            glRotatef(self.starangle, 0, 0, 1)
            self.show_stars()
            glRotatef(-self.starangle, 0, 0, 1)
        glRotatef(-self.angle, 1, 0, 0)
        if self.rotate and self.angle < 40:
            self.angle += 0.2
        prev = None
        for o, t in self.text:
            if o < -400:
                continue
            if prev is None:
                glTranslatef(0, o, 0)
            else:
                glTranslatef(0, o-prev, 0)
            prev = o
            t.draw()
        #for i in self.text:
        #    if i[1].autoscroll: i[0] = o+1
        self.text = [[o+1 if t.autoscroll else o, t] for o, t in self.text]
        if self.text and self.text[0][0] > 1000:
            self.text = self.text[1:]

    def genText(self, text, font):
        texts = text.split('\n')
        texts = [TextSprite(font, x.strip(), color=self.colour) 
                                                            for x in texts]
        if self.rotate:
            offset = -300
        else:
            offset = -400
        out = []
        for t in texts:
            out.append([offset, t])
            offset -= t.height
        return out

    def gen_stars(self):
        from random import random
        out = []
        for i in range(50):
            colour = (0.6 + random()/3,
                       0.6 + random()/3,
                       0.6 + random()/3)
            position = (500-random()*1000,500-random()*1000)
            out.append((position, colour))
        return out

    def show_stars(self):
        glPointSize(2)
        glBegin(GL_POINTS)
        for pos, col in self.stars:
            glColor3f (*col)
            glVertex2f(*pos)
        glEnd()


def setup():
    c = clock.Clock(60)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(60., 1., 1., 1000.)
    glEnable(GL_COLOR_MATERIAL)

    glMatrixMode(GL_MODELVIEW)
    glClearColor(0, 0, 0, 0)
    glColor4f(1, 1, 1, 1)

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glEnable(GL_BLEND)
    return c

def main():
    text = open(sys.argv[1]).read()
    texts = text.split('---\n')
    window = pyglet.window.Window(width=1024, height=768)
    c = setup()
    display = Displayer(texts)
    window.push_handlers(display)
    rotate = False

    while not window.has_exit:
        c.tick()
        window.dispatch_events()
        display.render()
        window.flip()


if __name__ == "__main__":
    main() 
